package org.abacus.db.v1.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.abacus.db.v1.m.Storage;
import org.abacus.db.v1.m.t.ReleaseType;

class StorageManager {
	static Map<String, Storage> storages = new HashMap<String, Storage>();

	static Connection getConnection(String target) throws SQLException {
		return getConnection(storages.get(target));
	}

	static void registerStorage(String target, Storage storage) {
		storages.put(target, storage);
	}

	static void removeStorage(String target) {
		storages.remove(target);
	}

	static Connection getConnection(Storage storage) throws SQLException {
		registerDriverClassName(storage);
		return DriverManager.getConnection(getUrl(storage), storage.getUser().getUsername(), storage.getUser()
				.getPassword());
	}

	private static void registerDriverClassName(Storage storage) {
		try {
			Class.forName(storage.getDatabase().getRelease().getReleaseVersion().getDriverClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private static String getUrl(Storage storage) {
		String url = null;
		if (ReleaseType.ORACLE == storage.getDatabase().getRelease().getReleaseType()) {
			url = "jdbc:oracle:thin:@" + storage.getNode().getAddress() + ":" + storage.getNode().getPort() + ":"
					+ storage.getDatabase().getDatabaseName();
		} else if (ReleaseType.MYSQL == storage.getDatabase().getRelease().getReleaseType()) {
			url = "jdbc:mysql://" + storage.getNode().getAddress() + ":" + storage.getNode().getPort() + "/"
					+ storage.getDatabase().getDatabaseName() + "?username=" + storage.getUser().getUsername()
					+ ";password=" + storage.getUser().getPassword()
					+ ";useUnicode=true&amp;characterEncoding=UTF-8&amp;mysqlEncoding=utf-8";
		} else if (ReleaseType.SQLSERVER == storage.getDatabase().getRelease().getReleaseType()) {

		} else {
			throw new RuntimeException("not support the release type.");
		}
		return url;
	}
}
